<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="92px">
      <el-form-item label="报工类型" prop="feedbackType">
        <el-input v-model="queryParams.feedbackType" placeholder="请输入报工类型" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="工作站名称" prop="workstationName">
        <el-input v-model="queryParams.workstationName" placeholder="请输入工作站名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="生产工单编号" prop="workorderCode">
        <el-input v-model="queryParams.workorderCode" placeholder="请输入生产工单编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="产品物料编码" prop="itemCode">
        <el-input v-model="queryParams.itemCode" placeholder="请输入产品物料编码" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="产品物料名称" prop="itemName">
        <el-input v-model="queryParams.itemName" placeholder="请输入产品物料名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="报工人" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入报工人" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="审核人" prop="recordUser">
        <el-input v-model="queryParams.recordUser" placeholder="请输入审核人" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-input v-model="queryParams.status" placeholder="请输入状态" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['feedback:feedback:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['feedback:feedback:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['feedback:feedback:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['feedback:feedback:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="feedbackList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="记录ID" align="center" prop="recordId" />
      <el-table-column label="报工类型" align="center" prop="feedbackType" />
      <el-table-column label="报工单编号" align="center" prop="feedbackCode" />
      <el-table-column label="工作站名称" align="center" prop="workstationName" />
      <el-table-column label="生产工单编号" align="center" prop="workorderCode" />
      <el-table-column label="工序名称" align="center" prop="processName" />
      <el-table-column label="产品物料编码" align="center" prop="itemCode" />
      <el-table-column label="产品物料名称" align="center" prop="itemName" />
      <el-table-column label="单位" align="center" prop="unitOfMeasure" />
      <el-table-column label="规格型号" align="center" prop="specification" />
      <el-table-column label="本次报工数量" align="center" prop="quantityFeedback" />
      <el-table-column label="报工人" align="center" prop="userName" />
      <el-table-column label="报工时间" align="center" prop="feedbackTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.feedbackTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="center" prop="recordUser" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- 1. 修改按钮：行状态符合 + 登录人是报工人/审核人 -->
          <el-button v-show="(scope.row.status === '未审批') &&
            (currentLoginUser === scope.row.userName || currentLoginUser === scope.row.recordUser)
            " link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['feedback:feedback:edit']">修改</el-button>

          <!-- 2. 删除按钮：同修改按钮权限 -->
          <el-button v-show="(scope.row.status === '未审批') &&
            (currentLoginUser === scope.row.userName || currentLoginUser === scope.row.recordUser)
            " link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['feedback:feedback:remove']">删除</el-button>

          <!-- 3. 审核按钮：行状态未审批 + 登录人是审核人 -->
          <el-button v-show="scope.row.status === '未审批' &&
            currentLoginUser === scope.row.recordUser
            " link type="primary" icon="Check" @click="handleRecord(scope.row)">审核</el-button>
        </template>
      </el-table-column>

    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageDto.current"
      v-model:limit="queryParams.pageDto.size" @pagination="getList" />

    <!-- 添加或修改生产报工记录对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="feedbackRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="报工类型" prop="feedbackType">
          <!-- <el-input style="width: 240px;" v-model="form.feedbackType" placeholder="请输入报工类型" /> -->
          <el-select v-model="form.feedbackType" placeholder="请输入报工类型" style="width: 240px">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-form-item label="报工单编号" prop="feedbackCode">
            <el-input style="width: 488px;" v-model="form.feedbackCode" placeholder="请输入报工单编号" />
          </el-form-item>
        </el-form-item>

        <el-form-item label="生产工单" prop="workorderCode">
          <el-input style="width: 170px;" v-model="form.workorderCode" placeholder="请输入生产工单编号" />
          <el-icon @click="innerVisibleMenu = true, getListWOrkorder()"
            style="border: 1px solid #DCDFE6;width: 30px;height: 30px;background-color: #F5F7FA;cursor: pointer;">
            <Search />
          </el-icon>

        </el-form-item>
        <el-form-item label="工作站" prop="workstationId">
          <el-input style="width: 170px;" v-model="form.workstationId" placeholder="请输入工作站名称" />
          <el-icon @click="innerVisibleJob = true, getStaList()"
            style="border: 1px solid #DCDFE6;width: 30px;height: 30px;background-color: #F5F7FA;cursor: pointer;">
            <Search />
          </el-icon>
        </el-form-item>
        <el-form-item label="生产任务" prop="taskCode">
          <el-input style="width: 170px;" v-model="form.taskCode" placeholder="请输入生产任务编号" />
          <el-icon @click="innerVisibleTask = true, getListTask()"
            style="border: 1px solid #DCDFE6;width: 30px;height: 30px;background-color: #F5F7FA;cursor: pointer;">
            <Search />
          </el-icon>
        </el-form-item>
        <el-form-item label="产品编码" prop="itemCode">
          <el-input style="width: 200px;" v-model="form.itemCode" placeholder="请输入产品物料编码" />
          <el-form-item label="产品名称" prop="itemName">
            <el-input style="width: 200px;" v-model="form.itemName" placeholder="请输入产品物料名称" />
          </el-form-item>
          <el-form-item label="单位" prop="unitOfMeasure">
            <el-input style="width: 200px;" v-model="form.unitOfMeasure" placeholder="请输入单位" />
          </el-form-item>
        </el-form-item>

        <el-form-item label="规格型号" prop="specification">
          <el-input v-model="form.specification" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="报工数量" prop="quantityFeedback">
          <el-input v-model="form.quantityFeedback" placeholder="请输入本次报工数量" />
        </el-form-item>
        <el-form-item label="报工人" prop="userName">
          <el-input style="width: 170px;" v-model="form.userName" placeholder="请输入报工人" />
          <el-icon @click="innerVisiblePeo = true, getUserList()"
            style="border: 1px solid #DCDFE6;width: 30px;height: 30px;background-color: #F5F7FA;cursor: pointer;">
            <Search />
          </el-icon>

        </el-form-item>
        <el-form-item label="报工时间" prop="feedbackTime">
          <el-date-picker clearable style="width: 200px;" v-model="form.feedbackTime" type="datetime"
            format="YYYY-MM-DD HH:mm:ss" placeholder="请选择报工时间" :editable="false">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审核人" prop="recordUser">
          <el-input style="width: 170px;" v-model="form.recordUser" placeholder="请输入审核人" disabled />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <!-- 内部控制生产工单对话框显示 -->
      <el-dialog v-model="innerVisibleMenu" width="1000" title="工单选择" append-to-body>
        <div class="app-container">
          <el-form :model="workQueryParams" ref="workorderQueryRef" :inline="true" v-show="showSearch"
            label-width="68px">
            <el-form-item label="工单编码" prop="workorderCode">
              <el-input v-model="workQueryParams.workorderCode" placeholder="请输入工单编码" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="工单名称" prop="workorderName">
              <el-input v-model="workQueryParams.workorderName" placeholder="请输入工单名称" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="产品编号" prop="productCode">
              <el-input v-model="workQueryParams.productCode" placeholder="请输入产品编号" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="workQueryParams.productName" placeholder="请输入产品名称" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="客户名称" prop="clientName">
              <el-input v-model="workQueryParams.clientName" placeholder="请输入客户名称" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleWorkorderQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetWorkorderQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-table v-loading="loading" :data="workorderList" @selection-change="handleSelectionWorkorderChange">
            <el-table-column type="selection" width="55" align="center" />
            <!-- <el-table-column label="工单ID" align="center" prop="workorderId" /> -->
            <el-table-column label="工单编码" align="center" prop="workorderCode" />
            <el-table-column label="工单名称" align="center" prop="workorderName" />
            <el-table-column label="工单来源" align="center" prop="orderSource" />
            <!-- <el-table-column label="订单编号" align="center" prop="orderId" /> -->
            <el-table-column label="产品编号" align="center" prop="productCode" />
            <el-table-column label="产品名称" align="center" prop="productName" />
            <el-table-column label="规格型号" align="center" prop="productSpc" />
            <el-table-column label="单位" align="center" prop="unitOfMeasure" />
            <el-table-column label="工单数量" align="center" prop="quantity" width="80" />
            <!-- <el-table-column label="客户编码" align="center" prop="clientCode" />
      <el-table-column label="客户名称" align="center" prop="clientName" /> -->
            <el-table-column label="需求日期" align="center" prop="requestDate" width="120">
              <template #default="scope">
                <span>{{ parseTime(scope.row.requestDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="totalWorkorder > 0" :total="totalWorkorder" v-model:page="workQueryParams.pageNum"
            v-model:limit="workQueryParams.pageSize" @pagination="getListWorkorder" />
          <el-button style="margin-left: 780px;margin-top: 30px;" type="primary" @click="confirmWorkorder">确
            认</el-button>
          <el-button style="margin-top: 30px;" @click="cancelWorkorder">关 闭</el-button>
        </div>
      </el-dialog>
      <!-- 内部控制工作站对话框显示 -->
      <el-dialog v-model="innerVisibleJob" width="1000" title="工作站选择" append-to-body>
        <el-form :model="queryStaParams" ref="stationQueryRef" :inline="true" v-show="showSearch" label-width="100px">
          <el-form-item label="工作站编码" prop="workstationCode">
            <el-input v-model="queryStaParams.workstationCode" placeholder="请输入工作站编码" clearable
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="所在车间名称" prop="workshopName">
            <el-select v-model="queryStaParams.workshopCode" placeholder="请选择车间" clearable style="width: 240px">
              <el-option v-for="item in workshopOptions" :key="item.workshopId" :label="item.workshopName"
                :value="item.workshopCode" />
            </el-select>
          </el-form-item>
          <el-form-item label="所属工序" prop="processName">
            <el-select v-model="queryStaParams.processCode" placeholder="请选择工序" clearable style="width: 240px">
              <el-option v-for="(item, index) in processCodeOptions" :key="item.processId" :label="item.processName"
                :value="item.processCode" :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleStaQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetStaQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="workstationList" @selection-change="handleSelectionStaChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="工作站ID" align="center" prop="workstationId" />
          <el-table-column label="工作站编码" align="center" prop="workstationCode" />
          <el-table-column label="工作站名称" align="center" prop="workstationName" />
          <el-table-column label="工作站地点" align="center" prop="workstationAddress" />
          <el-table-column label="所在车间名称" align="center" prop="workshopName" />
          <el-table-column label="工序名称" align="center" prop="processName" />
          <el-table-column label="备注" align="center" prop="remark" />
        </el-table>

        <pagination v-show="totalSta > 0" :total="totalSta" v-model:page="queryStaParams.pageNum"
          v-model:limit="queryStaParams.pageSize" @pagination="getStaList" />
        <el-button style="margin-left: 780px;margin-top: 30px;" type="primary" @click="confirmSta">确 认</el-button>
        <el-button style="margin-top: 30px;" @click="cancelSta">关 闭</el-button>
      </el-dialog>
      <!-- 内部控制生产任务对话框显示 -->
      <el-dialog v-model="innerVisibleTask" width="1000" title="生产任务选择" append-to-body>
        <el-table v-loading="loadingTask" :data="taskList" @selection-change="handleSelectionTaskChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="任务编号" align="center" prop="taskCode" />
          <el-table-column label="任务名称" align="center" prop="taskName" />
          <el-table-column label="工作站编号" align="center" prop="workstationCode" />
          <el-table-column label="工作站名称" align="center" prop="workstationId" />
          <el-table-column label="排产数量" align="center" prop="quantity" />
          <el-table-column label="已生产数量" align="center" prop="quantityProduced" />
          <el-table-column label="开始生产时间" align="center" prop="startTime" width="180">
            <template #default="{ row }">
              <span>{{ formatTime(row.startTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="生产时长" align="center" prop="duration" />
          <el-table-column label="完成生产时间" align="center" prop="endTime" width="180">
            <template #default="{ row }">
              <span>{{ formatTime(row.endTime) }}</span>
            </template>
          </el-table-column>
        </el-table>
        <el-button style="margin-left: 780px;margin-top: 30px;" type="primary" @click="confirmTask">确 认</el-button>
        <el-button style="margin-top: 30px;" @click="cancelTask">关 闭</el-button>
      </el-dialog>
      <!-- 内部控制报工人对话框显示 -->
      <el-dialog v-model="innerVisiblePeo" width="1000" title="报工人选择" append-to-body>
        <el-row :gutter="20">
          <splitpanes :horizontal="appStore.device === 'mobile'" class="default-theme">
            <!--部门数据-->
            <pane size="16">
              <el-col>
                <div class="head-container">
                  <el-input v-model="deptName" placeholder="请输入部门名称" clearable prefix-icon="Search"
                    style="margin-bottom: 20px" />
                </div>
                <div class="head-container">
                  <el-tree :data="deptOptions" :props="{ label: 'label', children: 'children' }"
                    :expand-on-click-node="false" :filter-node-method="filterNode" ref="deptTreeRef" node-key="id"
                    highlight-current default-expand-all @node-click="handleNodeClick" />
                </div>
              </el-col>
            </pane>
            <!--用户数据-->
            <pane size="84">
              <el-col>
                <el-form :model="userQueryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
                  <el-form-item label="用户名称" prop="userName">
                    <el-input v-model="userQueryParams.userName" placeholder="请输入用户名称" clearable style="width: 240px"
                      @keyup.enter="handleQuery" />
                  </el-form-item>
                  <el-form-item label="手机号码" prop="phonenumber">
                    <el-input v-model="userQueryParams.phonenumber" placeholder="请输入手机号码" clearable style="width: 240px"
                      @keyup.enter="handleQuery" />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                    <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                  </el-form-item>
                </el-form>

                <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionUserChange">
                  <el-table-column type="selection" width="50" align="center" />
                  <el-table-column label="用户编号" align="center" key="userId" prop="userId" v-if="columns[0].visible" />
                  <el-table-column label="用户名称" align="center" key="userName" prop="userName" v-if="columns[1].visible"
                    :show-overflow-tooltip="true" />
                  <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName" v-if="columns[2].visible"
                    :show-overflow-tooltip="true" />
                  <el-table-column label="部门" align="center" key="deptName" prop="dept.deptName"
                    v-if="columns[3].visible" :show-overflow-tooltip="true" />
                  <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber"
                    v-if="columns[4].visible" width="120" />
                  <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[6].visible" width="160">
                    <template #default="scope">
                      <span>{{ parseTime(scope.row.createTime) }}</span>
                    </template>
                  </el-table-column>
                </el-table>
                <pagination v-show="total > 0" :total="total" v-model:page="userQueryParams.pageNum"
                  v-model:limit="userQueryParams.pageSize" @pagination="getList" />
                <el-button style="margin-left: 780px;margin-top: 30px;" type="primary" @click="confirmUser">确
                  认</el-button>
                <el-button style="margin-top: 30px;" @click="cancelUser">关 闭</el-button>
              </el-col>
            </pane>
          </splitpanes>
        </el-row>
      </el-dialog>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" v-show="flag4" @click="submitForm">确 定</el-button>
          <el-button type="primary" @click="yesPass" v-show="flag3">审核通过</el-button>
          <el-button type="primary" @click="noPass" v-show="flag3">审核不通过</el-button>
          <el-button type="primary" @click="showS" v-show="shenpi">提交审批</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Feedback">
import { ElDatePicker, ElForm, ElFormItem } from 'element-plus' // 单独注册所需组件

import { listWorkorder, getWorkorder, delWorkorder, addWorkorder, updateWorkorder, getListBom, addWorkorderBom, getWorkInnerBomList } from "@/api/workorder/workorder"
import { listWorkstation, getWorkstation, delWorkstation, addWorkstation, updateWorkstation, listWorkshop, listProcess } from "@/api/workstation/workstation"
import useAppStore from '@/store/modules/app'
import { listFeedback, getFeedback, delFeedback, addFeedback, updateFeedback, getLeader } from "@/api/feedback/feedback"
// import { ref } from 'vue'
import { addMessage } from "@/api/system/sysmessage"
import { changeUserStatus, listUser, resetUserPwd, delUser, getUser, updateUser, addUser, deptTreeSelect } from "@/api/system/user";
import { listTask1, listTask, getTask, delTask, addTask, updateTask } from "@/api/task/task"
import { formatTime } from '@/utils/format';
import { tr } from 'element-plus/es/locales.mjs'
import useUserStore from '@/store/modules/user'
import { ref, onMounted } from 'vue' // 必须引入 onMounted

const userStore = useUserStore()
const currentLoginUser = ref('')

// 步骤2：组件挂载时调用 getInfo() 加载用户信息
onMounted(async () => {
  // 1. 先判断是否有 token（已登录），且 name 未加载（避免重复调用）
  if (userStore.token && !userStore.name) {
    try {
      await userStore.getInfo() // 关键：调用 getInfo() 加载 name、id 等信息
      console.log("Store 中加载的用户名：", userStore.name); // 此时能打印出用户名
    } catch (error) {
      console.error("加载用户信息失败：", error); // 排查接口是否有问题
    }
  }
  // 2. 赋值给 currentLoginUser（此时 userStore.name 已加载）
  currentLoginUser.value = userStore.name || ''
  console.log("当前登录人用户名：", currentLoginUser.value); // 现在能正常打印了
})
// 生产任务多选框选中数据
// 多选框选中任务数据
function handleSelectionTaskChange(selection) {
  ids.value = selection.map(item => item.recordId)
  single.value = selection.length != 1
  multiple.value = !selection.length
  selectedTaskItem.value = selection.length > 0 ? selection[0] : null;
}
const totalTask = ref(0)
const loadingTask = ref(true)
/** 查询生产任务列表 */
function getListTask() {
  loadingTask.value = true
  console.log(queryParamsTask.value);
  if (queryParamsTask.value.workorderId == null || queryParamsTask.value.workorderId == 'undefined') {
    proxy.$modal.msgWarning("请先选择工单");
    innerVisibleTask.value = false
    return
  }
  listTask1(queryParamsTask.value).then(response => {
    // console.log(response);
    // console.log(response.data);


    taskList.value = response.data
    console.log(taskList.value);

    totalTask.value = response.total
    loadingTask.value = false
  })
}
async function showS() {
  // proxy.$modal.msgSuccess("提交成功")
  await workOrderSH()
  open.value = false
  flag2.value = false
  showShen.value = true
}

//发送审核通知
async function workOrderSH() {
  const message = {
    messageTitle: "工单编号[" + form.value.workorderCode + "]有待审核的任务,任务编号为[" + form.value.taskCode + "]",
    messageType: "审核通知",
    messageLevel: "一般",
    status: "未处理",
    remark: form.value.remark,
    // attr1: form.value.quantity,
    createBy: form.value.recordUser,
    createTime: new Date(),
    updateTime: new Date(),
  }
  console.log("打印打印message", message);

  // 返回Promise，确保等待所有操作完成
  return proxy.$modal.confirm('是否确认通知审核？')
    .then(function () {
      return addMessage(message) // 等待addMessage完成
    })
    .then(() => {
      proxy.$modal.msgSuccess("通知成功")
    })
    .catch(() => {
      // 可以在这里处理取消的情况，比如抛出错误
      // throw new Error("用户取消了通知")
    })
}








function noPass() {
  // 1. 基础校验：确保有要更新的报工记录ID（否则后端无法定位数据）
  if (!form.value.recordId) {
    proxy.$modal.msgError("报工记录ID缺失,无法执行审核不通过操作");
    return;
  }

  // 2. 赋值状态（关键：确保状态值与后端定义一致，若后端用枚举需修改，如"REJECTED"）
  form.value.status = "未通过"; // 若后端不识别，改为后端要求的值（如"审核不通过"）

  // 3. 调用后端接口，同步状态到数据库（核心步骤）
  updateFeedback(form.value)
    .then(() => {
      // 4. 接口成功：提示+关闭弹窗+刷新列表（确保前端显示最新状态）
      proxy.$modal.msgSuccess("审核不通过操作成功");
      open.value = false; // 关闭弹窗

      // 重置按钮状态
      flag2.value = true;
      flag4.value = true;
      flag3.value = false;

      // 关键：刷新报工列表，显示后端更新后的状态
      getList();
    })
    .catch(error => {
      // 5. 接口失败：提示错误（便于排查问题）
      const errorMsg = error.response?.data?.msg || "审核不通过操作失败";
      proxy.$modal.msgError(errorMsg);
      console.error("审核不通过接口报错：", error); // 打印错误日志，方便定位问题
    });

  // （可选）任务关联校验（原逻辑保留，不影响状态修改）
  if (!form.value.taskId) {
    proxy.$modal.msgWarning("报工记录未关联生产任务，不影响审核结果"); // 改为warning，避免阻断操作
    // 注意：这里不能加return，否则会阻断上面的接口调用
  }
}
function yesPass() {
  // 1. 基础校验：避免无任务/无数量时执行
  if (!form.value.taskId) {
    proxy.$modal.msgError("报工记录未关联生产任务，无法审核通过");
    return;
  }
  const feedbackQty = Number(form.value.quantityFeedback);
  if (isNaN(feedbackQty) || feedbackQty <= 0) {
    proxy.$modal.msgError("报工数量必须是正数字");
    return;
  }

  // 2. 核心：将报工状态设为“已审核”（根据后端要求调整值）
  form.value.status = "已审核";

  // 3. 查找关联的生产任务
  const targetTask = taskList.value.find(task => task.taskId === form.value.taskId);
  if (targetTask) {
    // 计算更新后的已生产数量（若需累加历史报工数，改为：(targetTask.quantityProduced || 0) + feedbackQty）
    const newProducedQty = feedbackQty;

    // 业务校验：已生产数量不能超过排产数量（可选，根据需求保留）
    if (newProducedQty > targetTask.quantity) {
      proxy.$modal.msgError(`已生产数量(${newProducedQty})不能超过排产数量(${targetTask.quantity})`);
      return;
    }

    // -------------------------- 新增：状态判断逻辑 --------------------------
    // 更新已生产数量
    targetTask.quantityProduced = newProducedQty;
    // 判断：已生产数量 ≥ 排产数量 → 将生产任务状态改为“已完成”（需匹配后端状态字段和值）
    if (newProducedQty >= targetTask.quantity) {
      targetTask.status = "已完成"; // 关键：设置任务状态为“已完成”，若后端用枚举（如1=未完成/2=已完成），需改为对应值
      console.log(`生产任务【${targetTask.taskCode}】已完成（已生产：${newProducedQty}，排产：${targetTask.quantity}）`);
    }
    // ------------------------------------------------------------------------

    // 4. 先更新生产任务（含状态变更）→ 再更新报工状态（保证数据一致性）
    updateTask(targetTask)
      .then(() => {
        // 5. 同步报工状态到后端
        return updateFeedback(form.value);
      })
      .then(() => {
        // 6. 双接口成功：提示（含状态变更信息）+ 刷新列表
        const taskStatusTip = targetTask.status === "已完成" ? "，生产任务状态已改为「已完成」" : "";
        proxy.$modal.msgSuccess(`审核通过！报工状态已改为「已审核」${taskStatusTip}`);
        getList(); // 刷新报工列表
        getListTask(); // 刷新生产任务列表（显示最新状态）
        open.value = false;
      })
      .catch(error => {
        const errorMsg = error.response?.data?.msg || "操作失败";
        proxy.$modal.msgError(`审核失败：${errorMsg}`);
        console.error("审核流程错误:", error);
      });
  } else {
    proxy.$modal.msgWarning("未找到关联的生产任务，无法更新已生产数量");
  }
}
function confirmTask() {
  if (!selectedTaskItem.value) {
    proxy.$modal.msgWarning("请选择一个任务");
    return;
  }
  // 将选中的任务信息回填到表单
  console.log("renwu xinxi ", selectedTaskItem.value);

  const selectedTask = selectedTaskItem.value;
  form.value.taskId = selectedTask.taskId;
  form.value.taskCode = selectedTask.taskCode;
  form.value.taskName = selectedTask.taskName;
  form.value.quantity = selectedTask.quantity;
  console.log(form.value);

  // 关闭用户选择框，返回工单表单
  innerVisibleTask.value = false;
}

function cancelTask() {
  innerVisibleTask.value = false
}

/** 查询用户列表 */
function getUserList() {
  loading.value = true;
  listUser(proxy.addDateRange(userQueryParams.value, dateRange.value)).then(res => {
    loading.value = false;
    userList.value = res.rows;
    total.value = res.total;
  });
};
//回填用户信息
function confirmUser() {
  if (!selectedUserItem.value) {
    proxy.$modal.msgWarning("请选择一个用户");
    return;
  }
  // 将选中的物料信息回填到表单
  console.log(selectedUserItem.value);

  const selectedUser = selectedUserItem.value;
  console.log("nini", selectedUser);

  form.value.userName = selectedUser.userName;
  deptId.value = selectedUser.dept.deptId;
  console.log(deptId.value);
  getLeader(deptId.value).then(res => {
    console.log(res);
    form.value.recordUser = res.leader;

  })
  // 关闭用户选择框，返回工单表单
  innerVisiblePeo.value = false;
}
// 审核按钮
async function handleRecord(row) {
  flag3.value = true;
  flag4.value = false;

  try {
    // 1. 等待报工数据加载完成（拿到 form.workorderId 和 form.taskId）
    //await handleUpdate(row);
    form.value = row; // 加载报工数据（含 taskId、workorderId）
    open.value = true;
    shenpi.value = false;
    // 2. 关键：用报工关联的 workorderId 筛选，加载对应的生产任务
    if (form.value.workorderId) {
      // 设置生产任务查询参数：仅加载当前工单的任务
      queryParamsTask.value.workorderId = form.value.workorderId;
      // 调用 getListTask() 加载任务列表到 taskList
      await getListTask();
      console.log("加载的生产任务列表：", taskList.value);
    } else {
      proxy.$modal.msgWarning("报工记录未关联生产工单，无法加载生产任务");
    }
    // 3. 设置审核对话框标题
    title.value = "生产报工审批";
  } catch (error) {
    console.error("审核准备失败:", error);
    proxy.$modal.msgError("审核准备失败，请重试");
  }
}

function handleSelectionUserChange(selection) {
  ids.value = selection.map(item => item.workorderId)
  single.value = selection.length != 1
  multiple.value = !selection.length
  selectedUserItem.value = selection.length > 0 ? selection[0] : null;

}

//关闭用户选择框
function cancelUser() {
  innerVisiblePeo.value = false
}
const flag3 = ref(false)
const countBg = ref(0) //报工数量
const flag4 = ref(true)
const showShen = ref(false)
const flag2 = ref(true)
const deptId = ref(null)
const taskList = ref([])
const shenpi = ref(false)
const selectedUserItem = ref(null);
const dateRange = ref([]);
const userList = ref([]);
const { proxy } = getCurrentInstance()
const appStore = useAppStore()
// 列显隐信息
const columns = ref([
  { key: 0, label: `用户编号`, visible: true },
  { key: 1, label: `用户名称`, visible: true },
  { key: 2, label: `用户昵称`, visible: true },
  { key: 3, label: `部门`, visible: true },
  { key: 4, label: `手机号码`, visible: true },
  { key: 5, label: `状态`, visible: true },
  { key: 6, label: `创建时间`, visible: true }
]);
const workorderList = ref([])
/** 查询生产工单列表 */
function getListWOrkorder() {
  loading.value = true
  listWorkorder(workQueryParams.value).then(response => {
    console.log(response.rows);

    response.rows.forEach(row => {
      row.orderSource = row.orderSource == 1 ? '客户订单' : '库存备货'
    })

    workorderList.value = response.rows
    totalWorkorder.value = response.total
    loading.value = false
  })
}
function handleSelectionWorkorderChange(selection) {
  ids.value = selection.map(item => item.workorderId)
  single.value = selection.length != 1
  multiple.value = !selection.length
  selectedItem.value = selection.length > 0 ? selection[0] : null;

}

function cancelWorkorder() {
  innerVisibleMenu.value = false;
}

//确认选中生产工单并回填
function confirmWorkorder() {
  if (!selectedItem.value) {
    proxy.$modal.msgWarning("请选择一个生产工单");
    return;
  }
  // 将选中的生产工单信息回填到表单
  //console.log("选中的生产工单",selectedItem.value);

  const selectedWorkorder = selectedItem.value;
  //form.value.routeId = selectedWorkorder.workorderId; 
  form.value.workorderId = selectedWorkorder.workorderId;
  form.value.workorderCode = selectedWorkorder.workorderCode; // 回填【生产工单编号】
  form.value.workorderName = selectedWorkorder.workorderName;// 回填【生产工单名称】
  form.value.itemId = selectedWorkorder.itemId;
  form.value.itemCode = selectedWorkorder.productCode;       // 回填【产品物料编码】
  form.value.itemName = selectedWorkorder.productName;       // 回填【产品物料名称】
  form.value.specification = selectedWorkorder.productSpc;   // 回填【规格型号】
  form.value.unitOfMeasure = selectedWorkorder.unitOfMeasure;// 回填【单位】
  queryParamsTask.value.workorderId = selectedWorkorder.workorderId;
  console.log("生产任务查询参数：", queryParamsTask.value); // 验证是否赋值成功

  console.log(form.value);

  // 关闭生产工单选择框，返回工单表单
  innerVisibleMenu.value = false;

}
//搜索
function handleWorkorderQuery() {
  workQueryParams.value.pageNum = 1
  getListWOrkorder()
}

function resetWorkorderQuery() {
  // 1. 重置生产工单表单（使用唯一ref"workorderQueryRef"）
  proxy.resetForm("workorderQueryRef");

  // 2. 强制清空生产工单查询参数
  workQueryParams.value = {
    pageNum: 1, // 重置页码为1
    pageSize: 10,
    workorderCode: null,
    workorderName: null,
    orderType: null,
    quantity: null,
    orderSource: null,
    productCode: null,
    productName: null,
    productId: null,
    clientCode: null,
    clientName: null,
    requestDate: null,
  };

  // 3. 重置生产工单选中状态
  selectedItem.value = null;
  ids.value = [];
  single.value = true;
  multiple.value = true;

  // 4. 重新查询生产工单（显示初始数据）
  handleWorkorderQuery();
}

/** 查询工作站列表 */
function getStaList() {
  loading.value = true
  getWorkshopList()
  getProcessList()
  listWorkstation(queryStaParams.value).then(response => {
    console.log("工作站接口返回数据：", response.rows);
    workstationList.value = response.rows
    totalSta.value = response.total
    loading.value = false
  })
}
//查询车间列表
function getWorkshopList() {
  loading.value = true
  listWorkshop().then(response => {
    workshopOptions.value = response.data
    loading.value = false

  })
}
//查询工序列表
function getProcessList() {
  loading.value = true
  listProcess().then(response => {
    console.log("工序", response);
    processCodeOptions.value = response.data
    loading.value = false
  })
}

function handleSelectionStaChange(selection) {
  ids.value = selection.map(item => item.workstationId)
  single.value = selection.length != 1
  multiple.value = !selection.length
  selectedStaItem.value = selection.length > 0 ? selection[0] : null;

}

//回填工作站信息
function confirmSta() {
  if (!selectedStaItem.value) {
    proxy.$modal.msgWarning("请选择一个工作站");
    return;
  }

  // 将选中的物料信息回填到表单
  console.log(selectedStaItem.value);

  const selectedSta = selectedStaItem.value;
  form.value.workstationName = selectedSta.workstationName; // 回填【生产工单编号】
  form.value.workstationId = selectedSta.workstationId; // 回填【生产工单编号】

  console.log(form.value);

  // 关闭工作站选择框
  innerVisibleJob.value = false;

}

function cancelSta() {
  innerVisibleJob.value = false;
}

function handleStaQuery() {
  queryStaParams.value.pageNum = 1
  getStaList()
}

function resetStaQuery() {
  // 1. 重置工作站表单（使用唯一ref"stationQueryRef"）
  proxy.resetForm("stationQueryRef");

  // 2. 强制清空工作站查询参数
  queryStaParams.value = {
    pageNum: 1, // 重置页码为1
    pageSize: 10,
    workstationCode: null,
    workstationName: null,
    workstationId: null,
    workshopCode: null,
    workshopName: null,
    processCode: null,
    processName: null,
  };

  // 3. 重置工作站选中状态
  selectedStaItem.value = null;
  ids.value = [];
  single.value = true;
  multiple.value = true;

  // 4. 重新查询工作站（显示初始数据）
  handleStaQuery();
}

const processCodeOptions = ref([])//工序下拉列表
const workshopOptions = ref([])//车间下拉列表
const workstationList = ref([]) //工作站列表
const feedbackList = ref([])
const open = ref(false)
const selectedItem = ref('')
const selectedStaItem = ref('')
const selectedTaskItem = ref('')
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const totalWorkorder = ref(0) //生产工单专用
const totalSta = ref(0)  //工作站专用
const title = ref("")
const value = ref('')
const innerVisibleMenu = ref(false) // 内部控制生产工单对话框显示
const innerVisibleJob = ref(false)  //内部控制工作站对话框显示
const innerVisibleTask = ref(false)  //内部控制生产任务对话框显示
const innerVisiblePeo = ref(false)  //内部控制报工人对话框显示


const options = [
  {
    value: '1',
    label: '统一报工',
  },
  {
    value: '2',
    label: '自行报工',
  },

]
const data = reactive({
  form: {},
  queryParamsTask: {
    pageNum: 1,
    pageSize: 10,
    workorderId: undefined,
  },
  userQueryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
    phonenumber: undefined,
    status: undefined,
    deptId: undefined
  },
  queryParams: {
    pageDto: {
      current: 1,
      size: 10,
    },
    feedbackType: null,
    workstationName: null,
    workorderCode: null,
    itemCode: null,
    itemName: null,
    userName: null,
    recordUser: null,
    status: null,
    workstationId: null,
  },
  workQueryParams: {
    pageNum: 1,
    pageSize: 10,
    workorderCode: null,
    workorderName: null,
    orderType: null,
    quantity: null,
    orderSource: null,
    productCode: null,
    productName: null,
    productId: null,
    clientCode: null,
    clientName: null,
    requestDate: null,
    quantityGt: 0 // 新增：筛选排产数量>0的任务
  },
  queryStaParams: {
    pageNum: 1,
    pageSize: 10,
    workstationCode: null,
    workstationName: null,
    workstationId: null,
    workshopCode: null,
    workshopName: null,//所属车间
    processCode: null,
    processName: null,//所属工序
  },
  rules: {
    workstationId: [ // 新增：强制选择工作站
      { required: true, message: "请选择工作站", trigger: "blur" }
    ],
    feedbackType: [
      { required: true, message: "报工类型不能为空", trigger: "blur" }
    ],
    taskCode: [
      { required: true, message: "生产任务编号不能为空", trigger: "blur" }
    ],
    quantityFeedback: [
      { required: true, message: "本次报工数量不能为空", trigger: "blur" }
    ],
    userName: [
      { required: true, message: "报工人不能为空", trigger: "blur" }
    ],
    feedbackTime: [
      { required: true, message: "报工时间不能为空", trigger: "blur" }
    ],
    recordUser: [
      { required: true, message: "审核人不能为空", trigger: "blur" }
    ],
  }
})

const { queryParamsTask, userQueryParams, queryStaParams, workQueryParams, queryParams, form, rules } = toRefs(data)

/** 查询生产报工记录列表 */
function getList() {
  loading.value = true
  listFeedback(queryParams.value).then(response => {
    console.log("查询的数据", response);

    feedbackList.value = response.data.records
    total.value = response.data.pageDto.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    recordId: null,
    feedbackType: null,
    feedbackCode: null,
    workstationId: null,
    workstationCode: null,
    workstationName: null,
    workorderId: null,
    workorderCode: null,
    workorderName: null,
    routeId: null,
    routeCode: null,
    processId: null,
    processCode: null,
    processName: null,
    taskId: null,
    taskCode: null,
    itemId: null,
    itemCode: null,
    itemName: null,
    unitOfMeasure: null,
    specification: null,
    quantity: null,
    quantityFeedback: null,
    quantityQualified: null,
    quantityUnquanlified: null,
    quantityUncheck: null,
    userName: null,
    nickName: null,
    feedbackChannel: null,
    feedbackTime: null,
    recordUser: null,
    recordNick: null,
    status: null,
    remark: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("feedbackRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageDto.current = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.recordId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  shenpi.value = false
  title.value = "添加生产报工记录"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  console.log("zhehangshuju", row);

  reset()
  const _recordId = row.recordId || ids.value
  return getFeedback(_recordId).then(response => {
    form.value = response.data; // 加载报工数据（含 taskId、workorderId）
    open.value = true;
    shenpi.value = true;
    title.value = "修改生产报工记录";
    // 这里可以拿到报工关联的 workorderId，后续用于加载生产任务
    console.log("报工关联的工单ID：", form.value.workorderId);
    console.log("报工关联的任务ID：", form.value.taskId); // 确认是否有 taskId
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["feedbackRef"].validate(valid => {
    if (valid) {
      console.log("提交的表单数据:", form.value); // 添加这行检查数据
      console.log("保存数据", form.value);

      if (form.value.recordId != null) {
        updateFeedback(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addFeedback(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _recordIds = row.recordId || ids.value
  proxy.$modal.confirm('是否确认删除生产报工记录编号为"' + _recordIds + '"的数据项？').then(function () {
    return delFeedback(_recordIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('feedback/feedback/export', {
    ...queryParams.value
  }, `feedback_${new Date().getTime()}.xlsx`)
}

getList()
</script>
